package com.example.sell.interlayer;

import com.example.sell.bean.ProductCategory;
import com.example.sell.bean.ProductInfo;
import com.example.sell.common.ResultVOUtil;
import com.example.sell.service.CategoryService;
import com.example.sell.service.ProductService;
import com.example.sell.vo.ProductInfoVO;
import com.example.sell.vo.ProductVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 *  中间层 用来处理多个service层的业务处理
 */
@Service
public class ProductCategoryService {

    @Autowired
    private ProductService productService;

    @Autowired
    private CategoryService categoryService;


    public List<ProductVO> list() {
        /**查询所有在架商品*/
        List<ProductInfo> productInfoList = productService.findUp();
        /** 查询类目（一次性查询）*/

        List<Integer> categoryList = new ArrayList<>();
        for (ProductInfo productInfo : productInfoList) {
            categoryList.add(productInfo.getCategoryType());
        }
        List<ProductCategory> productCategoryList = categoryService.findByCategoryTypeIn(categoryList);
        /** 拼装查找数据*/
        List<ProductVO> productVOList = new ArrayList<>();
        //遍历商品类目信息
        for (ProductCategory productCategory : productCategoryList) {
            ProductVO productVO = new ProductVO();
            productVO.setCategoryName(productCategory.getCategoryName());
            productVO.setCategoryType(productCategory.getCategoryType());

            //遍历商品信息
            List<ProductInfoVO> productInfoVOList = new ArrayList<>();
            for (ProductInfo productInfo : productInfoList) {
                if (productInfo.getCategoryType().equals(productVO.getCategoryType())) {
                    ProductInfoVO productInfoVO = new ProductInfoVO();
                    BeanUtils.copyProperties(productInfo, productInfoVO);
                    productInfoVOList.add(productInfoVO);
                }

            }
            productVO.setProductInfoVOList(productInfoVOList);
            productVOList.add(productVO);
        }

        return productVOList;
    }

    /**
     * 查找单个商品商品类目
     *
     * @param categoryId 类目id
     * @return
     */
    public ResultVOUtil<Optional<ProductCategory>> findOne(Integer categoryId) {
        return categoryService.findOne(categoryId);
    }

    /**
     * 添加/更新商品类目
     * @param productCategory
     * @return
     */
    public ResultVOUtil<ProductCategory> save(@Valid ProductCategory productCategory) {
        return categoryService.save(productCategory);
    }

}
